import Request from '@/utils/luch-request/index.js'
import baseUrl from './config.js'
import storage from "@/utils/storage"
const http = new Request()
import onLogin from '@/utils/login'

http.setConfig((config) => {
	config.baseURL = baseUrl
	return config
})

http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	const {
		custom: {
			isLoading
		},
	} = config
	if (isLoading) {
		// uni.showLoading({
		// 	title: '加载中...',
		// 	mask: true
		// });
	}
	if (config.method === "POST" && config.data) {
		config.params = config.data.params
	}
	const TOKEN = storage.getStorage('access_token') || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo0OTM5LCJsb2dpbl90eXBlIjo5LCJvcGVuSWQiOiJvYU5rZzZjUEVuaXZYdmx0WkdqNTYtaGZYdTRFIiwic2VydmVyX21vZGUiOiJkZWJ1ZyIsImlzcyI6ImF4ZV9tYWdpY19taXJyb3IiLCJleHAiOjE3MzczNTg3Nzh9.8ZpghmRlTdHrlUhVQDkVbwk9ZoaavcR-LKxJg8QmBDY'
	config.header['token'] = TOKEN
	// config.header['version'] = 'v1'
	console.log(config.baseURL, config.url, config, 'qingqiu')
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

http.interceptors.response.use(
	res => {
		console.log(res, '响应')
		// uni.hideLoading()
		const {
			code,
			msg
		} = res.data


		if (code === 1012 || code === 1002 || code === 205) {
			uni.showToast({
				title: '正在重新连接魔镜服务，请稍后重试…',
				icon: "none",
				duration: 2000
			});
			storage.removeStorage('access_token')
			onLogin()
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/home/index'
				});
			}, 2000)

		}
		return res.data
	}, error => {
		const {
			statusCode
		} = error
		let msg = ''
		switch (statusCode) {
			case 404:
				msg = `${statusCode}（未找到）`
				break;
			case 500:
				msg = `${statusCode}（服务器内部错误）`
				break;
			default:
				break;
		}

		uni.showToast({
			title: msg || 'error',
			icon: "none",
			duration: 2000
		});
		// uni.hideLoading()
		return Promise.reject(error);
	}
)


export default http
